package id.co.rho.scoring.cid.server.servlet;

import gwtupload.server.exceptions.UploadActionException;
import id.co.rho.scoring.cid.server.service.UploadModelService;
import id.co.rho.scoring.cid.server.util.AppContext;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.context.ApplicationContext;

public class UploadModelServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		FileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		List items = null;
		ApplicationContext context = AppContext.getApplicationContext();
		UploadModelService uploadModelService = context
				.getBean(UploadModelService.class);
		String responseText = "failed to process the file ...";
		Boolean valid;
		String fieldName = null;
		String fieldType = null;
		try {
			items = upload.parseRequest(request);
		} catch (FileUploadException e) {
			e.printStackTrace();
		}
		Iterator it = items.iterator();
		while (it.hasNext()) {
			FileItem item = (FileItem) it.next();
			try {
				if (item.isFormField()) {
					String fieldString = item.getString();
					if (item.getFieldName().equalsIgnoreCase("fieldName")) {
						fieldName = fieldString;
					} else if (item.getFieldName()
							.equalsIgnoreCase("fieldType")) {
						fieldType = fieldString;
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		Iterator it2 = items.iterator();
		while (it2.hasNext()) {
			FileItem item = (FileItem) it2.next();
			try {
				if (!item.isFormField()) {
					try {
						File file = File.createTempFile("upload-", ".tmp");
						item.write(file);
						valid = uploadModelService.uploadModelExcel(
								new FileInputStream(file.getAbsoluteFile()),
								fieldName, fieldType);
						if (valid) {
							uploadModelService.saveModel();
						} else {
							String filename = "upload-failed.txt";
							response.setContentType("text/plain; charset=UTF-8");
							response.setCharacterEncoding("UTF-8");
							response.setHeader("Content-Disposition",
									"attachment; filename=\"" + filename + "\"");
							OutputStream outputStream;
							try {
								outputStream = response.getOutputStream();
								PrintStream printStream = new PrintStream(
										outputStream);
								printStream.print(responseText);
								printStream.flush();
								printStream.close();
							} catch (IOException e) {
								e.printStackTrace();
							}

						}
					} catch (Exception e) {
						e.printStackTrace();
						throw new UploadActionException(e);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

}
